from flask_restful import Resource, reqparse
from werkzeug.datastructures import FileStorage
from resources import api, docs
from flask_apispec import doc, MethodResource
from common import utils
from flask import send_file


class AttachmentListResource(MethodResource, Resource):

    def __init__(self):
        
        self.parses = reqparse.RequestParser()
        self.parses.add_argument("attachment", required=True, type=FileStorage, location="files", help="请选择上传文件")

    @doc(description="upload file api", tags=["文件上传"])
    def post(self):
        
        attachment_file = self.parses.parse_args().get("attachment")
        file_path = utils.get_attachment_path().joinpath(attachment_file.filename)
        attachment_file.save(file_path)
        return {"message": "ok", "code":200}

    
class AttachmentResource(MethodResource, Resource):
    @doc(description="down file api", tags=["文件下载"])
    def get(self, filename):
        file_path = utils.get_attachment_path().joinpath(filename)
        if not file_path.exists():
            return {"message": "error, the file is not exists", "code":404}
        return send_file(file_path)


api.add_resource(AttachmentListResource, "/attachments")
api.add_resource(AttachmentResource, "/attachments/<filename>")
docs.register(AttachmentListResource)
docs.register(AttachmentResource)